package com.fudan.biz.data.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fudan.biz.data.dao.BigDataSourceDao;
import com.fudan.biz.data.dao.FieldMetaDao;
import com.fudan.biz.data.entity.BigDataSource;
import com.fudan.es.entity.FieldMeta;
import com.fudan.es.service.IndexAdminService;
import com.fudan.framework.base.BaseController.PageBean;
import com.fudan.framework.base.BaseDao;
import com.fudan.framework.base.DaoService;

@Service
public class BigDataSourceService extends DaoService<BigDataSource> {

	@Autowired
	private BigDataSourceDao bigDataSourceDao;
	@Autowired
	private IndexAdminService indexAdminService;
	@Autowired
	private FieldMetaDao fieldMetaDao;

	public List<Map<String, Object>> getInfoList(PageBean pageBean) {
		return bigDataSourceDao.getInfoList((pageBean.getPage() - 1)*pageBean.getSize(), pageBean.getSize());
	}

	public List<Map<String, Object>> getInfoList(String query, PageBean pageBean) {
		return bigDataSourceDao.getInfoList(query, (pageBean.getPage() - 1)*pageBean.getSize(), pageBean.getSize());
	}

	public Long countInfoList(String query) {
		return bigDataSourceDao.countInfoList(query);
	}

	@Transactional
	@Override
	public Boolean add(BigDataSource t) {
		try {
			bigDataSourceDao.save(t);
			Integer dwId = t.getDwId();
			Integer dsId = t.getId();
			String index = t.getPath();
			Map<String, Object> mappings = indexAdminService.getFieldMapping(dwId, index);
			List<FieldMeta> fieldList = new ArrayList<>();
			indexAdminService.parseProperties(fieldList, null, mappings);
			indexAdminService.fillAbility(fieldList, index,dwId);
			for (FieldMeta fieldMeta : fieldList) {
				fieldMeta.setDsId(dsId);
			}
			fieldMetaDao.saveAll(fieldList);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return true;
	}

	@Transactional
	@Override
	public Boolean delete(String id) {
		fieldMetaDao.deleteByDsId(id);
		return super.delete(id);
	}

	public Long countInfoList() {
		return bigDataSourceDao.countInfoList();
	}

	public Map<String, Object> getInfo(String id) {
		return bigDataSourceDao.getInfo(id);
	}

	@Override
	protected BaseDao<BigDataSource> injectDao() {
		return bigDataSourceDao;
	}

}
